<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-alert
      title="添加商品信息"
      type="info"
      center
      show-icon
      :closable="false"
    >
    </el-alert>
    <!-- 步骤条区域 -->
    <el-steps
      :space="200"
      :active="parseInt(activeIndex)"
      finish-status="success"
      align-center
    >
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- tab栏区域 -->
    <el-form
      :model="addGoodsForm"
      :rules="addGoodsRules"
      ref="addGoodsRef"
      label-width="100px"
      class="demo-ruleForm"
      label-position="top"
    >
      <el-tabs
        tab-position="left"
        v-model="activeIndex"
        :before-leave="beforeleave"
        @tab-click="tabclick"
      >
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addGoodsForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input
              v-model="addGoodsForm.goods_price"
              type="number"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input
              v-model="addGoodsForm.goods_weight"
              type="number"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input
              v-model="addGoodsForm.goods_number"
              type="number"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              v-model="addGoodsForm.goods_cat"
              :options="cateList"
              :props="cascaderProps"
              @change="handleChange"
              ref="cascaderRef"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form-item
            :label="item.attr_name"
            v-for="item in manyTable"
            :key="item.attr_id"
          >
            <!-- 复选框组 -->
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                :label="item1"
                v-for="(item1, i1) in item.attr_vals"
                :key="i1"
                border
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form-item
            :label="item.attr_name"
            v-for="item in onlyTable"
            :key="item.attr_id"
          >
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            :action="uploadImgUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headers"
            :on-success="handleSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
          <el-button type="primary" class="btn_add" @click="add"
            >添加商品</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <!-- 图片预览对话框 -->
    <el-dialog title="提示" :visible.sync="imgdialogVisible" width="50%">
      <img :src="imgUrl" alt="" class="img_preview" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      //   添加商品表单对象
      addGoodsForm: {
        //   商品名称
        goods_name: '',
        // 商品价格
        goods_price: 0,
        // 商品重量
        goods_weight: 0,
        // 商品数量
        goods_number: 0,
        // 分类id
        goods_cat: [],
        // 图片列表
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      //   添加商品表单验证规则
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }

        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }

        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }

        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }

        ],
        goods_cat: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }

        ]
      },
      //   分类数据
      cateList: [],
      //   级联选择器的配置参数
      cascaderProps: {
        label: "cat_name",
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      //   动态参数
      manyTable: [],
      //   静态参数
      onlyTable: [],
      // 上传图片的URL地址
      uploadImgUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片的请求头
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制图片预览的显示与隐藏
      imgdialogVisible: false,
      // 图片预览的图片地址
      imgUrl: ''

    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }

  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类失败！')
      }
      this.cateList = res.data
      console.log(this.cateList);
    },
    // 级联选择框选择变化事件
    handleChange() {
      console.log(this.addGoodsForm.goods_cat);
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
      this.$refs.cascaderRef.dropDownVisible = false;


    },
    // tab标签发送切换事件
    beforeleave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },
    // tab标签点击事件
    async tabclick(res) {
      if (res.name === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数失败！')
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        });
        this.manyTable = res.data
        console.log(this.manyTable);
      }
      else if (res.name === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数失败！')
        }
        this.onlyTable = res.data
        console.log(this.onlyTable);
      }
    },
    // 图片预览处理函数
    handlePreview(file) {
      // console.log(file);
      this.imgUrl = file.response.data.url
      this.imgdialogVisible = true
    },
    // 图片移除事件处理函数
    handleRemove(file) {
      const filePath = file.response.data.tmp_path
      const i = this.addGoodsForm.pics.findIndex(x => {
        x.pic === filePath
      })
      this.addGoodsForm.pics.splice(i, 1)
      console.log(this.addGoodsForm);
    },
    // 图片上传成功事件处理函数
    handleSuccess(res) {
      let imgObj = { pics: res.data.tmp_path }
      this.addGoodsForm.pics.push(imgObj)
      console.log(this.addGoodsForm);
    },
    // 添加商品事件处理
    add() {
      this.$refs.addGoodsRef.validate(async volid => {
        if (!volid) {
          return this.$message.error('请填写必填项！')
        }
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        this.manyTable.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addGoodsForm.attrs.push(newInfo)
        })

        this.onlyTable.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        form.attrs = this.addGoodsForm.attrs
        console.log(form);
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  }

}
</script>
<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-step__title {
  font-style: 13px;
}
.el-checkbox {
  margin: 0 10px 0 0;
}
.el-input {
  width: 600px;
}
.el-cascader {
  width: 600px;
}
.img_preview {
  width: 60%;
  height: 60%;
}
.btn_add {
  margin-top: 15px;
}
</style>